<template>
  <div class="container">
    <!-- 地址 -->
    <div class="address">
      <van-address-list
        :list="addressData"
        default-tag-text="默认"
        class="address_list"
        :switchable="false"
      />
      <van-divider
        :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 0' }"
        dashed
      />
    </div>
    <!-- 购物车 -->
    <div class="goods_list">
      <van-card
        v-for="item in goodsList"
        :num="item.count"
        :price="(item.goods_info.price / 100).toFixed(2)"
        :desc="item.goods_info.detail_info"
        :title="item.goods_info.name"
        :thumb="item.goods_info.pic_url"
      />
    </div>
    <!-- 底部 -->
    <van-submit-bar
      :price="countPrice"
      button-text="生成订单"
      @submit="show = true"
    >
      <template #tip>
        <!-- 备注 -->
        <van-field
          v-model="remark"
          rows="2"
          autosize
          label="备注"
          type="textarea"
          show-word-limit
        />
      </template>
    </van-submit-bar>
    <!-- 付款动作面板 -->
    <van-action-sheet
      v-model:show="show"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      @cancel="onCancel"
      @select="onSelect"
    />
  </div>
</template>

<script setup>
import { getAddressList } from "@/api/address";
import { cartDelete } from "@/api/cart";
import useCartInfo from "@/stores/useCartInfo";
import { computed, onMounted, ref, watchEffect } from "@vue/runtime-core";
import { storeToRefs } from "pinia";
import { showSuccessToast } from "vant";
import { useRoute, useRouter } from "vue-router";
import { orderAdd } from "@/api/order";
import { getGoodsDetail } from "@/api/goods";

let route = useRoute();
let router = useRouter();

let cartStore = useCartInfo();
let { list } = storeToRefs(cartStore);

// 不能写成对象！
let addressData = ref([]);
let goodsList = ref([]);
let remark = ref("");

const actions = [
  { name: "微信", pay_type: 1 },
  { name: "支付宝", pay_type: 2 },
  { name: "云闪付", pay_type: 3 },
];
let show = ref(false);

onMounted(async () => {
  // 调用接口所有的地址
  let arr = (await getAddressList({ page: 1, limit: 100 })).data.list;
  // 过滤出选中的地址(路由传来的id是字符串 ==)
  let addressArr = arr.filter((item) => item.id == route.query.addressId);
  addressData.value = addressArr.map((item) => {
    return {
      id: item.id,
      name: item.name,
      tel: item.phone,
      address: item.province + item.city + item.town + item.detail,
      isDefault: item.is_default === 1,
    };
  });

  // 从详情下单
  if (route.query.goodsId) {
    // 获取商品详情
    let goodsInfo = (await getGoodsDetail({ id: route.query.goodsId })).data;
    let goodsItem = {
      count: 1, //从商品详情直接下单 默认买一个
      goods_info: goodsInfo,
      goods_id: route.query.goodsId,
    };
    // 拼接goodsList数据并塞到详情，实现商品显示
    goodsList.value = [goodsItem];
  }
});

watchEffect(() => {
  // 从购物车下单
  if (route.query.chosenGoods) {
    let goodsIds = route.query.chosenGoods.split(",");
    goodsList.value = list.value.filter((item) =>
      goodsIds.includes(item.id.toString())
    );
  }
});

let countPrice = computed(() => {
  let countPrice = 0;
  goodsList.value.forEach((item) => {
    countPrice = countPrice + item.count * item.goods_info.price;
  });
  return countPrice;
});

let onCancel = async () => {
  const data = {
    remark: remark.value,
    status: "1", // 待支付
    price: countPrice.value,
    order_goods_infos: goodsList.value.map((item) => {
      return {
        goods_id: item.goods_id,
        count: item.count,
      };
    }),
    addressId: addressData.value[0].id,
  };
  // 调用接口传递数据生成订单
  await orderAdd(data);
  // 判断下单途径
  if (route.query.chosenGoods) {
    // 删除已下单商品
    cartDelete({ ids: goodsList.value.map((item) => item.id) });
    // 调用action 更新购物车仓库数据
    cartStore.getCartInfo();
  }
  router.replace("/home");
};

let onSelect = async (action, index) => {
  // 付款链接没做，后续补
  const data = {
    pay_type: action.pay_type,
    remark: remark.value,
    status: "2",
    price: countPrice.value,
    order_goods_infos: goodsList.value.map((item) => {
      return {
        goods_id: item.goods_id,
        count: item.count,
      };
    }),
    addressId: addressData.value[0].id,
  };
  await orderAdd(data);
  showSuccessToast("下单成功");
  if (route.query.chosenGoods) {
    cartDelete({ ids: goodsList.value.map((item) => item.id) });
    cartStore.getCartInfo();
  }
  router.replace("/home");
};
</script>

<style lang="scss" scoped>
.container {
  // 底部bar 遮盖van-address-list的bar底部
  --van-submit-bar-z-index: 100;
  --van-address-list-add-button-z-index: 1;
  --van-submit-bar-tip-background: #f0f0f0;
  .address {
    padding-top: 20px;
    background-color: #fff;
    .address_list {
      --van-address-list-padding: 0;
      //   :deep  样式穿透   更改组件库内部的元素样式
      :deep(.van-badge__wrapper) {
        display: none;
      }
    }
  }
  .submit_box {
    background-color: #fff;
    bottom: 0;
    left: 0;
    right: 0;
    position: fixed;
    padding: 10px;
  }
}
</style>
